package com.demo.core.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import Decoder.BASE64Decoder;

import com.demo.base.model.Upfiles;
import com.demo.base.pojo.TempVo;
import com.demo.base.util.DateTimeUtil;
import com.demo.base.util.FileUtil;
import com.demo.base.util.MathExtend;
import com.demo.base.util.StringUtil;
import com.demo.base.util.UUIDGenerator;
import com.demo.core.service.UploadService;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

	@Autowired
	UploadService uploadService;
	

/*	*//**
	 * 跳转到多文件上传页面
	 * @param userInfo
	 * @return
	 *//*
	@RequestMapping("/uploadFilePage")
	public ModelAndView uploadFilePage() {
		ModelAndView mav = new ModelAndView("/common/uploadFile");
		return mav;
	}

	*//**
	 * 上传页面
	 * @return
	 *//*
	@RequestMapping("/uploadifyPage")
	public ModelAndView uploadifyPage() {
		ModelAndView mav = new ModelAndView("/common/uploadify");
		return mav;
	}
	*//**
	 * 上传页面(网站使用)
	 * @return
	 *//*
	@RequestMapping("/uploadifyWebPage")
	public ModelAndView uploadifyWebPage() {
		ModelAndView mav = new ModelAndView("/common/uploadifyWeb");
		return mav;
	}
	
	*//**
	 * 新增附件
	 * @param request
	 * @return
	 *//*
	@ResponseBody
	@RequestMapping("/addUpfiles")
	public Map<String, Object> addUpfiles(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("files");
			// 文件名
			String fileName = file.getOriginalFilename();
			// 文件大小
			Long fileSize = file.getSize();
			// 后缀
			String fileExt = FileUtil.getExtend(fileName);
			 如果不是允许的附件类型，直接返回 
			if (!FileUtil.getAllowFileTypes().contains(fileExt)) {
				return map;
			}
			String basepath = FileUtil.getUploadBasePath();
			 所有附件都保存到uploads 不存在则新增文件夹 
			File f = new File(basepath);
			if (!f.exists()) {
				f.mkdir();
			}
			String path = File.separator + "uploads";
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			 每年一个文件夹 
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			 每月一个文件夹 
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			 每天一个文件夹 
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			path = path + File.separator + UUIDGenerator.getUUID() + "." + fileExt.toLowerCase();

			DataOutputStream out = new DataOutputStream(new FileOutputStream(basepath + path));// 存放文件的绝对路径
			InputStream is = null;// 附件输入流
			is = file.getInputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = is.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			is.close();
			out.close();

			// 附件信息存库
			Upfiles upfiles = new Upfiles();
			upfiles.setFilename(fileName);
			upfiles.setFilepath(path);
			upfiles.setFileExt(fileExt.toLowerCase());
			upfiles.setSizeb(fileSize.intValue());
			String sizeM = MathExtend.divide(String.valueOf(upfiles.getSizeb()), String.valueOf(1024), 2);
			String dw = "K";
			if (Float.parseFloat(sizeM) > 1024) {
				sizeM = MathExtend.divide(sizeM, String.valueOf(1024), 2);
				dw = "M";
				if (Float.parseFloat(sizeM) > 1024) {
					sizeM = MathExtend.divide(sizeM, String.valueOf(1024), 2);
					dw = "G";
				}
			}
			upfiles.setSizem(sizeM + dw);
			Integer id = uploadService.addFile(upfiles);
			upfiles.setId(id);
			// 保存附件二进制信息
			FileData fileData = new FileData();
			BeanUtilEx.copyIgnoreNulls(upfiles, fileData);
			fileData.setUpfilesId(id);
			// 如果附件较大，存库耗时过长影响用户操作。存库的动作开启单独线程处理
//			new Thread(new FileInsertThread(uploadService, fileData)).start();

			// 构造返回页面的信息
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> s = new HashMap<String, Object>();
			s.put("id", upfiles.getId());
			s.put("name", fileName);
			s.put("size", fileSize);
			s.put("url", "javascript:void(0)");
			s.put("deleteUrl", "/upload/delFile?id=" + upfiles.getId() + "&sid=" + StringUtil.delNull(request.getParameter("sid")));
			s.put("deleteType", "DELETE");
			map.put("files", s);
			list.add(s);
			map.put("files", list);
		} catch (Exception e) {
			if (!e.getClass().getSimpleName().equals("ClassCastException")) {
				e.printStackTrace();
			}
		}
		return map;
	}*/
	
	@ResponseBody
	@RequestMapping("/addUploadifyFile")
	public Map<String, Object> addUploadifyFile(HttpServletRequest request,@RequestBody TempVo tempVo) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			//String basepath = "F:\\uploads\\91_sp_upload";
			String basepath = request.getRealPath("\\") + "WEB-INF";
			/* 所有附件都保存到uploads 不存在则新增文件夹 */
			File f = new File(basepath);
			if (!f.exists()) {
				f.mkdir();
			}
			String path = File.separator + "uploads";
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			/* 每年一个文件夹 */
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			/* 每月一个文件夹 */
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			/* 每天一个文件夹 */
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}

			String[] files = tempVo.getImage()[0].split(",");
			String[] temp1 = files[0].split(";");
			String[] temp2 = temp1[0].split("/");
			//获取文件类型
			String fileType = temp2[1];
			//解密base64文件
			byte[] bytes = this.decodeBASE64(files[1]);
				//生成文件
				String fileName = UUIDGenerator.getUUID() + "." + fileType.toLowerCase();
				path = path + File.separator + fileName;

				DataOutputStream out = new DataOutputStream(new FileOutputStream(basepath + path));// 存放文件的绝对路径
				out.write(bytes);
				out.flush();
				out.close();

				// 附件信息存库
				Upfiles upfiles = new Upfiles();
				upfiles.setFilename(fileName);
				upfiles.setFilepath(path);
				upfiles.setFileExt(fileType.toLowerCase());
				//upfiles.setSizeb(Integer.parseInt(String.valueOf(file.getSize())));
				//String sizeM = MathExtend.divide(String.valueOf(upfiles.getSizeb()), String.valueOf(1024), 2);
				//String dw = "K";
//				if (Float.parseFloat(sizeM) > 1024) {
//					sizeM = MathExtend.divide(sizeM, String.valueOf(1024), 2);
//					dw = "M";
//					if (Float.parseFloat(sizeM) > 1024) {
//						sizeM = MathExtend.divide(sizeM, String.valueOf(1024), 2);
//						dw = "G";
//					}
//				}
				//upfiles.setSizem(sizeM + dw);
				uploadService.addUpfiles(upfiles);
				// 构造返回页面的信息
				//List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				map.put("id", upfiles.getId());
				map.put("name", fileName);
				//map.put("size", file.getSize());
				map.put("url", "javascript:void(0)");
				map.put("deleteUrl", "/upload/delFile?id=" + upfiles.getId() + "&sid=" + StringUtil.delNull(request.getParameter("sid")));
				map.put("deleteType", "DELETE");
				map.put("filepath",path);
				map.put("files", upfiles);
			//}
		} catch (Exception e) {
			if (!e.getClass().getSimpleName().equals("ClassCastException")) {
				e.printStackTrace();
			}
		}
		return map;
	}
	/**
	 * 上传附件（网站使用）
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addUploadifyFileWeb")
	public Map<String, Object> addUploadifyFileWeb(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String basepath =   FileUtil.getUploadBasePath();
			//String basepath = FileUtil.getRootPath()+"WEB-INF";
			/* 所有附件都保存到uploads 不存在则新增文件夹 */
			File f = new File(basepath);
			if (!f.exists()) {
				f.mkdir();
			}
			String path = File.separator + "uploads";
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			/* 每年一个文件夹 */
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			/* 每月一个文件夹 */
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}
			/* 每天一个文件夹 */
			path = path + File.separator + DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd);
			f = new File(basepath + path);
			if (!f.exists()) {
				f.mkdir();
			}

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件名
				// System.out.println("key: " + entity.getKey());
				MultipartFile file = entity.getValue();
				String fileName = file.getOriginalFilename();
				String fileExt = FileUtil.getExtend(fileName);
				if (!FileUtil.getAllowFileTypes().contains(fileExt)) {
					return map;
				}
				path = path + File.separator + UUIDGenerator.getUUID() + "." + fileExt.toLowerCase();

				DataOutputStream out = new DataOutputStream(new FileOutputStream(basepath + path));// 存放文件的绝对路径
				InputStream is = null;// 附件输入流
				is = file.getInputStream();
				byte[] buf = new byte[1024];
				int len = 0;
				while ((len = is.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				is.close();
				out.close();

				// 附件信息存库
				Upfiles upfiles = new Upfiles();
				upfiles.setFilename(fileName);
				upfiles.setFilepath(path);
				upfiles.setFileExt(fileExt.toLowerCase());
				upfiles.setSizeb(Integer.parseInt(String.valueOf(file.getSize())));
				String sizeM = MathExtend.divide(String.valueOf(upfiles.getSizeb()), String.valueOf(1024), 2);
				String dw = "K";
				if (Float.parseFloat(sizeM) > 1024) {
					sizeM = MathExtend.divide(sizeM, String.valueOf(1024), 2);
					dw = "M";
					if (Float.parseFloat(sizeM) > 1024) {
						sizeM = MathExtend.divide(sizeM, String.valueOf(1024), 2);
						dw = "G";
					}
				}
				upfiles.setSizem(sizeM + dw);
				uploadService.addUpfiles(upfiles);
				// 构造返回页面的信息
				//List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				map.put("id", upfiles.getId());
				map.put("name", fileName);
				map.put("size", file.getSize());
				map.put("url", "javascript:void(0)");
				map.put("deleteUrl", "/upload/delFile?id=" + upfiles.getId() + "&sid=" + StringUtil.delNull(request.getParameter("sid")));
				map.put("deleteType", "DELETE");
				map.put("filepath",path);
				map.put("files", upfiles);
			}
		} catch (Exception e) {
			if (!e.getClass().getSimpleName().equals("ClassCastException")) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	//解密方法
	//FileOutSteam写文件传byte或者int,String转byte在写文件会不成功。
	public byte[] decodeBASE64(String str) throws Exception {
		if (str != null) {
			return new BASE64Decoder().decodeBuffer(str);
		}
		return null;
	}
}